<template>
  <div>
    <MyHeader :headerProps="headerProps" />
    <MyGoods
      :gObj="gObj"
      v-for="(gObj, index) in goodsList"
      :key="index"
      @changeNum="changeNumFn"
      @changeState="changeStateFn"
    />
    <MyFooter
      :totalNum="totalNum"
      :totalPrice="totalPrice"
      :goodsList="goodsList"
      @changeChecked="changeCheckedFn"
    />
  </div>
</template>

<script>
import MyFooter from './components/MyFooter.vue'
import MyGoods from './components/MyGoods.vue'
import MyHeader from './components/MyHeader.vue'
export default {
  components: {
    MyFooter,
    MyGoods,
    MyHeader,
  },
  data() {
    return {
      goodsList: [],
      headerProps: {
        title: '购物车',
        bgc: 'pink',
        color: 'white',
      },
    }
  },
  // 获取数据
  created() {
    this.$axios({
      url: '/api/cart', // 请求地址
      method: 'get', // 请求的方法
    }).then((res) => {
      this.goodsList = res.data.list
    })
  },
  methods: {
    //改变商品数量
    changeNumFn(n, i) {
      this.goodsList.forEach((item) => {
        if (item.id === i) {
          item.goods_count = n
          return
        }
      })
    },
    // 改变商品选中状态
    changeStateFn(i) {
      this.goodsList.forEach((item) => {
        if (item.id === i) {
          item.goods_state = !item.goods_state
          return
        }
      })
    },
    // 根据全选矿状态改变其他复选框
    changeCheckedFn(val){
      this.goodsList.forEach(i=>i.goods_state=val)
    }
  },
  computed: {
    // 计算总数
    totalNum() {
      return this.goodsList
        .filter((item) => item.goods_state)
        .reduce((sum, val) => {
          return sum + val.goods_count
        }, 0)
    },
    // 计算总价
    totalPrice() {
      return this.goodsList
        .filter((item) => item.goods_state)
        .reduce((sum, val) => {
          return sum + val.goods_price * val.goods_count
        }, 0)
    }
  }
}
</script>

<style></style>
